package com.zhx.basis.juc;

import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class 延时队列 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("3");
        list.add("2");
        list.add("4");
        list.add("5");
        list.add("6");
        ExecutorService es = Executors.newFixedThreadPool(3);//3个线程的线程池
        DelayQueue<MyDelay> delays = new DelayQueue<>();
        delays.offer(new MyDelay("1", "1n", 1000));
        delays.offer(new MyDelay("2", "1n", 2000));
        delays.offer(new MyDelay("3", "3n", 3000));
        delays.offer(new MyDelay("4", "4n", 4000));
        delays.offer(new MyDelay("5", "5n", 5000));
        delays.offer(new MyDelay("6", "6n", 6000));
        delays.offer(new MyDelay("7", "7n", 7000));
        delays.offer(new MyDelay("8", "8n", 12000));
        while (true){
            if (delays.size()<=0){
                break;
            }
            try {
                //从加入任务的那一刻开始exectime后执行
                delays.take();
                System.out.println(System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}

class MyDelay implements Delayed {
    private String id;
    private String name;
    private long execTime;

    public MyDelay(String id, String name, long execTime) {
        this.id = id;
        this.name = name;
        //现在的纳米时间加上指定传入的毫秒时间,这个毫秒时间是经过convert转换的,这个时间用于后续触发事件使用
        this.execTime = TimeUnit.NANOSECONDS.convert(execTime, TimeUnit.MILLISECONDS) + System.nanoTime();
    }

    //任务的时间减去当前时间,看看还剩多久
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.execTime - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    //
    @Override
    public int compareTo(Delayed o) {
        MyDelay msg = (MyDelay) o;
        return this.execTime > msg.execTime ? 1 : (this.execTime < msg.execTime ? -1 : 0);
    }
}